<template>
  <div class="main-box scroll">
    <TreeFilter
      label="name"
      search-label="资源组名称"
      :data="treeFilterData"
      :default-value="defaultData"
      :show-node-contextmenu="true"
      @change="changeTreeFilter"
      @node-contextmenu="rightClick"
    >
    </TreeFilter>
    <!-- 树形控件右键组件 -->
    <div v-show="menuShow" class="tree_rightmenu" :style="{ ...rightMenu }">
      <el-menu class="el-menu-vertical-demo" @select="selectMenuNode">
        <el-menu-item id="menuitem" index="1" style="font-size: 12px" @click="openOrgDialog('addOrEditTreeRef', true)">
          <template #title>
            <span>新增本级</span>
          </template>
        </el-menu-item>
        <el-menu-item id="menuitem" index="2" style="font-size: 12px" @click="openOrgDialog('addOrEditTreeRef', true)">
          <template #title>
            <span>新增下级</span>
          </template>
        </el-menu-item>
        <el-menu-item id="menuitem" index="3" style="font-size: 12px" @click="openOrgDialog('addOrEditTreeRef', false)">
          <template #title>
            <span>编辑</span>
          </template>
        </el-menu-item>
        <el-menu-item index="4" style="font-size: 12px" @click="deleteOrg()">
          <template #title>
            <span>删 除</span>
          </template>
        </el-menu-item>
      </el-menu>
    </div>
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="资产列表"
        highlight-current-row
        :columns="columns"
        :request-api="getCollect"
        :pagination="true"
        :show-summary="false"
        :init-param="initParam"
        :indent="20"
        :has-colums="hasColums"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 4, xl: 4 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button :icon="Plus" type="primary" @click="openDialog('addOrEditRef', {}, false, false)"> 新增 </el-button>
          <el-button
            :icon="Plus"
            type="primary"
            :disabled="scope.selectedList.length !== 1"
            @click="openDialog('addOrEditRef', scope.selectedList[0], true, false)"
          >
            复制新增
          </el-button>
          <el-button type="primary" :disabled="scope.selectedList.length !== 1" @click="launchTicket(scope.selectedList[0].id)">
            发起工单
          </el-button>
        </template>
        <template #operation="scope">
          <el-button type="primary" link @click="openDialog('detailRef', scope.row)"> 详情 </el-button>
          <el-button type="primary" link @click="openDialog('upholdRef', scope.row)"> 维护 </el-button>
          <el-button type="primary" link @click="openDialog('addOrEditRef', scope.row, false, true)"> 编辑 </el-button>
          <el-button type="primary" link @click="deleteAccount([scope.row])">删除</el-button>
        </template>
      </ProTable>
      <!--      <modalAssociatedUsers ref="associatedUsersRef" />-->
      <modalAddOrEdit ref="addOrEditRef" @refresh="refresh" :data="tableSelected" :is-copy="isCopy" :is-editor="isEditor" />
      <modalDetail :data="tableSelected" ref="detailRef" />
      <modalUphold :data="tableSelected" @refresh="refresh" ref="upholdRef" />
      <modalTreeAddOrEdit ref="addOrEditTreeRef" @refresh="getTypeList" />
    </div>
  </div>
</template>

<script setup lang="ts" name="assetOverview">
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import {
  getBaseColumns,
  getCollect,
  getFilterElements,
  deleteAssetList,
  getAssetCollect,
  deleteGroupTerminate
} from "@/api/modules/asset";
import { onMounted, reactive, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { useHandleData } from "@/hooks/useHandleData";
import modalAddOrEdit from "@/views/asset/asset_overview/component/createForm.vue";
import modalDetail from "@/views/asset/asset_overview/component/modal_detail.vue";
import modalUphold from "@/views/asset/asset_overview/component/modal_uphold.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import modalTreeAddOrEdit from "@/views/asset/asset_overview/component/modal_tree_add_or_edit.vue";

const router = useRouter();
const defaultData = ref<any>([]);
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 表格配置项
let columns = reactive<ColumnProps[]>([
  { type: "selection", width: 80 },
  { type: "index", label: "#", width: 80 }
]);
let baseColumns = ref<any>([]);
// let operableColumns = ref<any>([]);
let hasColums = ref<boolean>(false);
const isCopy = ref<boolean>(false);
const isEditor = ref<boolean>(false);
const tableSelected = ref<object>({});
// 请求资产类型树
const treeFilterData = ref<any>([]);
const getTypeList = async () => {
  const { data } = await getAssetCollect();
  treeFilterData.value = data;
  defaultData.value = [data[0].id];
};
const changeTreeFilter = (data: string) => {
  proTable.value!.pageable.page = 1;
  initParam.groups_id = data;
};
// 组织树右键点击事件
const curMenuNode = ref<any>("");
const menuShow = ref<boolean>(false);
const rightMenu = ref<any>({});
const rightClick = (e, data) => {
  curMenuNode.value = data;
  menuShow.value = false; // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
  if (data.id) {
    menuShow.value = true;
    e.preventDefault(); //关闭浏览器右键默认事件
    rightMenu.value = { top: e.pageY + "px", left: e.pageX + "px" };
    document.addEventListener("click", ev => {
      // ev.stopImmediatePropagation()
      if (ev.target !== document.querySelector(".el-menu-item.is-active")) {
        foo();
      }
    });
  }
};
const foo = () => {
  // 取消鼠标监听事件 菜单栏
  menuShow.value = false;
  document.removeEventListener("click", foo); // 关掉监听，
};
// 删除组织
const deleteOrg = () => {
  ElMessageBox.confirm("是否确定删除所选分组？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const res = await deleteGroupTerminate(curMenuNode.value.id);
    if (res) {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
    }
  });
};
// 新建编辑组织机构
const addOrEditTreeRef = ref<InstanceType<typeof modalTreeAddOrEdit> | null>(null);
const openOrgDialog = (ref: string, isAdd: boolean) => {
  if (ref == "addOrEditTreeRef") addOrEditTreeRef.value?.openDialog(curMenuNode.value, isAdd, curLevel);
};
let curLevel = 1;
const selectMenuNode = data => {
  curLevel = data;
};
// 获取基础配置列
const getBaseColumnsArr = async () => {
  hasColums.value = false;
  const { data } = await getBaseColumns();
  baseColumns.value = data;
  getSearchConfig();
};
// 获取可操作列
// const getColumnsArr = async () => {
//   operableColumns.value = [];
//   const { data } = await getColumns();
//   operableColumns.value = data;
//   baseColumns.value.forEach(item => {
//     const obj = operableColumns.value.find(a => a.key === item.key);
//     if (obj) {
//       item["isFilterEnum"] = true;
//     } else {
//       item["isFilterEnum"] = false;
//     }
//   });
//   getSearchConfig();
// };
let searchArr: any = [];
// 获取筛选项
const getSearchConfig = async () => {
  const { data } = await getFilterElements();
  searchArr = data;
  baseColumns.value.map(item => {
    const i = searchArr.find(a => a.key === item.key);
    const column = {
      prop: item.key,
      label: item.name,
      minWidth: 100,
      isFilterEnum: true
    };
    if (i) {
      column["search"] = { el: i.type, label: i.name };
    }
    columns.push(column);
    hasColums.value = true;
  });
  columns.push({ prop: "operation", label: "操作", fixed: "right", minWidth: 150 });
};

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ groups_id: "" });
// 发起工单
const launchTicket = id => {
  router.replace({ name: "ticket_newTicket", query: { asset_id: id, ticketType: "asset" } });
};
// 新增
const addOrEditRef = ref<InstanceType<typeof modalAddOrEdit> | null>(null);
const detailRef = ref<InstanceType<typeof modalDetail> | null>(null);
const upholdRef = ref<InstanceType<typeof modalUphold> | null>(null);
const openDialog = (ref: string, data?: object, copy?: boolean, editor?: boolean) => {
  switch (ref) {
    case "addOrEditRef":
      isCopy.value = copy || false;
      isEditor.value = editor || false;
      tableSelected.value = data || {};
      addOrEditRef.value?.openDialog();
      break;
    case "detailRef":
      tableSelected.value = data || {};
      detailRef.value?.openDialog();
      break;
    case "upholdRef":
      tableSelected.value = data || {};
      upholdRef.value?.openDialog();
      break;
  }
};
// 删除
const deleteAccount = async (params: any[]) => {
  const toDoList: string[] = [];
  const notToDoList: string[] = [];
  const ids: number[] = params.map(item => {
    if (item.id) {
      toDoList.push(item.name);
    } else {
      notToDoList.push(item.name);
    }
    return item.id;
  });
  await useHandleData(deleteAssetList, ids[0], ["删除", ""], toDoList, notToDoList);
  proTable.value?.getTableList();
  proTable.value?.clearSelection();
};
// const refresh = () => {
//   proTable.value?.getTableList();
// };
const refresh = () => {
  proTable.value?.getTableList();
};
onMounted(async () => {
  getBaseColumnsArr();
  getTypeList();
});
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
